package com.learning.controller.admin;


import com.learning.constant.JwtClaimsConstant;
import com.learning.dto.LoginDTO;
import com.learning.entity.Admin;
import com.learning.properties.JwtProperties;
import com.learning.result.Result;
import com.learning.service.IAdminService;
import com.learning.utils.JwtUtil;
import com.learning.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author itRao
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/admin")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "通用接口")
public class AdminController {

    private final IAdminService adminService;
    private final JwtProperties jwtProperties;

    /**
     * 管理员登录
     *
     * @param loginDTO
     * @return
     */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("管理员登录：{}", loginDTO);
        Admin admin = adminService.login(loginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        LoginVO loginVO = LoginVO.builder()
                .id(admin.getId())
                .userName(admin.getUsername())
                .token(token)
                .build();

        return Result.success(loginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("管理员退出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

}
